package com.ray.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.DuplicateOrderUpdateRecordBean;
import com.ray.bean.OrderInfoDetailBean;
import com.ray.bean.UserBean;
import com.ray.mapper.DuplicateOrderUpdateRecordsMapper;
import com.ray.mapper.FeedOrderMapper;
import com.ray.mapper.OrderMapper;
import com.ray.util.RedirectUrlUtil;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.weixin.WeixinTemplateList;
import com.ray.util.weixin.WeixinTemplateSender;

/**
 * 备份订单被采购人员修改的记录信息
 * @author libin
 *
 */
@Service
public class DuplicateOrderUpdateRecordsService {
	
	@Autowired
	DuplicateOrderUpdateRecordsMapper duplicateOrderUpdateRecordsMapper;
	@Autowired
	WeiXinPeopleService weiXinPeopleService;
	@Autowired
	WeiXinService weiXinService;
	@Autowired
	BasicDataService basicDataService;
	@Autowired
	FeedOrderMapper feedOrderMapper;
	@Autowired
	ApprovalService approvalService;
	
	public void addDuplicateOrderUpdateRecords(DuplicateOrderUpdateRecordBean duplicateOrderUpdateRecordBean,Map<String,Object> map,boolean haveSendMessage) {
		Assert.notNull(duplicateOrderUpdateRecordBean.getOrderId(), "订单编号为空");
		Assert.notNull(duplicateOrderUpdateRecordBean.getLineNo(), "行号为空");
		Assert.notNull(duplicateOrderUpdateRecordBean.getMaterialType(), "物料类型为空");
		Assert.notNull(duplicateOrderUpdateRecordBean.getMaterialFactory(), "仓位为空");
		Assert.notNull(duplicateOrderUpdateRecordBean.getCompany(), "公司为空");
		duplicateOrderUpdateRecordBean.setIsApproval(0);
		int row = duplicateOrderUpdateRecordsMapper.addDuplicateOrderUpdateRecords(duplicateOrderUpdateRecordBean);
		Assert.isTrue(row>0, "插入失败");
		if(haveSendMessage) {
			//发送消息
			String titleText = "订单物料信息修改申请待审核";
			String titleType= "待审核信息";
			String bodyMessage = "订单物料信息修改申请(请到电脑页面查询)";
			this.sendUpdateOrderDetailMes(duplicateOrderUpdateRecordBean.getOrderId(),titleText,titleType,bodyMessage,false,map);
		}
	}
	
	public void sendUpdateOrderDetailMes(String orderId,String titleText,String titleType,String bodyMessage,boolean isBom,Map<String,Object> map ) {
		DuplicateOrderUpdateRecordBean duplicateOrderUpdateRecordBean = new DuplicateOrderUpdateRecordBean();
		duplicateOrderUpdateRecordBean.setOrderId(orderId);
		duplicateOrderUpdateRecordBean.setCompany(map.get("loginCompany").toString());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = sdf.format(new Date());
		Set<String> openIds = new HashSet<String>();
		if(!isBom) {
			String openId = duplicateOrderUpdateRecordsMapper.getOrderCreateUserIdOnOpenIdByOrderId(duplicateOrderUpdateRecordBean);
			openIds.add(openId);
		}else {
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("type", 9);
			paramMap.put("loginUserId", map.get("loginUserId"));
			paramMap.put("loginCompany", map.get("loginCompany"));
			//获取登录者的审核人
			List<String> approvalList = approvalService.getApprovalUserIdByLoginUserId(paramMap);
			if(approvalList==null || approvalList.size()==0) {
				return;
			}
			paramMap.put("userIds", approvalList);
			//通过用户ids获取openIds
			List<String> openIdList = weiXinPeopleService.getOpenIdByUserIds(paramMap);
			openIds.addAll(openIdList);
		}
		if(openIds.size()==0) {
			return;
		}
		String accessToken = null;
		try {
			accessToken = weiXinService.getAccessToken(null);
			com.alibaba.fastjson.JSONObject json=WeixinTemplateList.packJsonWatiApproval(titleText, titleType, map.get("loginUserName").toString(), map.get("loginUserPhone").toString(),dateString,bodyMessage , null, null, null, null, null, null, null, null);
			for(String openId:openIds) {
				WeixinTemplateSender.sendWechatmsgToUser(openId, WeiXinParamesUtil.watiApprovalTemplateID, null, json, accessToken);
			}
		} catch (RuntimeException e) {
		} 
	}
	
	//判断订单物料与库存物料是否一致 
	public boolean orderAndMaterialIsEqually(OrderInfoDetailBean order,OrderInfoDetailBean updateAfterOrder) {
		if(order.getMaterialCode()!=null && !"".equals(order.getMaterialCode().trim())) {
			//如果原订单物料代码不为空 ,并且补全后物料代码改变了,那么就是改变了物料
			if(!order.getMaterialCode().trim().equals(updateAfterOrder.getMaterialCode().trim())) {
				return false;
			}
		}else {
			//如果物料代码是空的
			//原色号不为空
			if(order.getIsReadColor()==1) {
				if(order.getColor()!=null && !"".equals(order.getColor())) {
					if(!order.getColor().equals(updateAfterOrder.getColor()==null?"":updateAfterOrder.getColor())) {
						return false;
					}
				}
				//原颜色描述不为空
				if(order.getColorDescription()!=null && !"".equals(order.getColorDescription())) {
					//不校验物料表颜色描述和订单颜色描述问题
					/*if(!order.getColorDescription().equals(updateAfterOrder.getColorDescription()==null?"":updateAfterOrder.getColorDescription())) {
						return false;
					}*/
				}
			}
			if(order.getMaterialModel()!=null && !"".equals(order.getMaterialModel())) {
				if(!order.getMaterialModel().equals(updateAfterOrder.getMaterialModel()==null?"":updateAfterOrder.getMaterialModel())) {
					return false;
				}
			}
		}
		return true;
	}
	
	//改变备份记录的isBom
	public void changeIsBom(DuplicateOrderUpdateRecordBean duplicateOrderUpdateRecordBean) {
		int row = duplicateOrderUpdateRecordsMapper.updateDuplicateOrderRecords(duplicateOrderUpdateRecordBean);
		Assert.isTrue(row>0, "修改备份记录状态失败");
	}
	
	//获取备份记录list
	public List<DuplicateOrderUpdateRecordBean> getDuplicateOrderUpdateRecordsListByIds(Map<String, Object> map) {
		Assert.notNull(map.get("ids"), "ids为空");
		Assert.notNull(map.get("loginCompany"),"公司为空");
		return duplicateOrderUpdateRecordsMapper.getDuplicateOrderUpdateRecordsList(map);
	}
	
	//改变备份记录的审核状态
	public void changeIsApprovalById(Map<String,String> map) {
		Assert.notNull(map.get("id"), "id为空");
		Assert.notNull(map.get("loginCompany"),"公司为空");
		checkCanApproval(map);
		DuplicateOrderUpdateRecordBean dourb = duplicateOrderUpdateRecordsMapper.getDuplicateOrderDataById(map);
		Assert.isTrue(dourb !=null && dourb.getIsApproval()==0, "改订单记录已经审核,请勿重复操作");
		int row = duplicateOrderUpdateRecordsMapper.changeIsApprovalById(map);
		Assert.isTrue(row>0, "审核订单失败");
		//补全物料
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("loginCompany", map.get("loginCompany"));
		paramMap.put("loginUserId", map.get("loginUserId"));
		paramMap.put("materialCode", dourb.getMaterialCode());
		paramMap.put("id", dourb.getOrderDetailId());
		Assert.notNull(dourb.getOrderDetailId(), "订单id为空");
		int orderRow = basicDataService.updateOrderInfoDetailByCompanyMaterialCode(paramMap);
		Assert.isTrue(orderRow>0, "补全订单信息失败");
	}
	
	//查询备份记录分页
	public DatatablesViewPageBean<DuplicateOrderUpdateRecordBean> getDuplicateOrderUpdateRecordsListPage(Map<String, Object> map) {
		DatatablesViewPageBean<DuplicateOrderUpdateRecordBean> datatablesViewPageBean = new DatatablesViewPageBean<DuplicateOrderUpdateRecordBean>();
		List<DuplicateOrderUpdateRecordBean> dataList = duplicateOrderUpdateRecordsMapper.getDuplicateOrderUpdateRecordsList(map);
		int count = duplicateOrderUpdateRecordsMapper.getDuplicateOrderUpdateRecordsListCount(map);
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setReturnData(dataList);
		return datatablesViewPageBean;
	}
	
	//校验订单修改是否审核
	public void chechIsApproval(OrderInfoDetailBean orderInfoDetail,String loginCompany) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("loginCompany", loginCompany);
		map.put("orderId", orderInfoDetail.getOrderNo());
		map.put("lineNo", orderInfoDetail.getLineNo());
		map.put("materialFactory", orderInfoDetail.getMaterialFactory());
		map.put("materialType", orderInfoDetail.getMaterialType());
		map.put("isApproval", "0");
		List<DuplicateOrderUpdateRecordBean> dataList = duplicateOrderUpdateRecordsMapper.getDuplicateOrderUpdateRecordsList(map);
		Assert.isTrue(dataList==null || dataList.size()==0,"该订单物料信息被修改,请先审核" );
	}

	public boolean checkExists(OrderInfoDetailBean orderInfoDetail, String loginCompany) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("loginCompany", loginCompany);
		map.put("orderId", orderInfoDetail.getOrderNo());
		map.put("lineNo", orderInfoDetail.getLineNo());
		map.put("materialFactory", orderInfoDetail.getMaterialFactory());
		map.put("materialType", orderInfoDetail.getMaterialType());
		map.put("isApproval", "0");
		List<DuplicateOrderUpdateRecordBean> dataList = duplicateOrderUpdateRecordsMapper.getDuplicateOrderUpdateRecordsList(map);
		return dataList!=null && dataList.size()>0;
	}

	public void deleteDuplicateOrder(Map<String, String> map) {
		Assert.notNull(map.get("id"), "id为空");
		Assert.notNull(map.get("loginCompany"), "公司名为空");
		checkCanApproval(map);
		int row = duplicateOrderUpdateRecordsMapper.deleteDuplicateOrder(map);
		Assert.isTrue(row>0, "退回订单物料备份信息失败");
	}
	
	//校验用户是否可审核备份记录
	public void checkCanApproval(Map<String,String> map) {
		Assert.notNull(map.get("id"), "id为空");
		Assert.notNull(map.get("loginCompany"),"公司为空");
		DuplicateOrderUpdateRecordBean dourb = duplicateOrderUpdateRecordsMapper.getDuplicateOrderDataById(map);
		String orderCreateUserName = duplicateOrderUpdateRecordsMapper.getOrderCreateUserByOrderId(dourb);
		Assert.isTrue(orderCreateUserName.equals(map.get("loginUserName")), "非订单制单人,无权审核");
	}
}
